package com.copa.provider.music.qq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.copa.api.BaseRequest;
import com.copa.api.HttpEngine;
import com.copa.constant.Constants;
import com.copa.entity.Music;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.copa.constant.MusicType.QQ;
import static com.copa.provider.music.qq.QQMusicApi.GUID;
import static com.copa.provider.music.qq.QQMusicApi.UIN;

class QQSearchMusicRequest extends BaseRequest<List<Music>> {
    private final String mKeyword;
    private static final int PAGE_SIZE = Constants.PAGE_SIZE;
    private final int mPage;
    private static final String SONG_URL_PREFIX = "https://y.qq.com/n/ryqq/songDetail/";

    public QQSearchMusicRequest(String keyword, int page) {
        mKeyword = keyword;
        mPage = page;
    }

    @Override
    protected Request buildRequest() {
        //HttpUrl.Builder urlBuilder = HttpUrl.parse("http://c.y.qq.com/soso/fcgi-bin/search_for_qq_cp").newBuilder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse("http://c.y.qq.com/soso/fcgi-bin/client_search_cp").newBuilder();
        urlBuilder.addQueryParameter("w", mKeyword);
        urlBuilder.addQueryParameter("p", String.valueOf(mPage));
        urlBuilder.addQueryParameter("n", String.valueOf(PAGE_SIZE));
        urlBuilder.addQueryParameter("aggr", String.valueOf(1));
        urlBuilder.addQueryParameter("cr", String.valueOf(1));
        urlBuilder.addQueryParameter("n", String.valueOf(0));
        // 请求参数更新
        //urlBuilder.addQueryParameter("format", "json");

        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(urlBuilder.build());
        requestBuilder.addHeader("User-Agent", QQMusicApi.USER_AGENT);
        requestBuilder.addHeader(Constants.REFERER, "http://m.y.qq.com");
        requestBuilder.get();
        final Request request = requestBuilder.build();
        return request;
    }

    @Override
    protected List<Music> parseResult(Response response) throws IOException {
        String data = responseBodyToString(response);
        // 去掉callback()字符串，留下json串
        data = data.substring(data.indexOf("callback(") + 9, data.length() - 1);
        JSONObject json = JSONObject.parseObject(data);
        JSONArray musicArray = json.getJSONObject("data").getJSONObject("song").getJSONArray("list");
        List<Music> musicList = new ArrayList<>();
        for (Object musicObj : musicArray) {
            JSONObject musicJsonObject = JSONObject.parseObject(musicObj.toString());
            Music music = Music.builder()
                    .title(musicJsonObject.getString("songname"))
                    // qq音乐的链接经常换，所以我这里懒得弄了...
                    .musicUrl(SONG_URL_PREFIX + musicJsonObject.getString("songmid"))
                    .brief(musicJsonObject.getString("lyric"))
                    .jumpUrl(SONG_URL_PREFIX + musicJsonObject.getString("songmid"))
                    .type(QQ.getAlias())
                    .pictureUrl(getImgUrl(musicJsonObject.getString("albumid")))
                    .summary(JSONObject.parseObject(musicJsonObject.getJSONArray("singer").getString(0)).getString("name"))
                    .build();
            musicList.add(music);
        }
        return musicList;
    }

    /**
     * 获取音乐url
     * @param songMid 音乐id
     * @return
     */
//    private String getMusicUrl(String songMid) {
//        String filename = "C400" + songMid + ".m4a";
//
//        String tokenUrl = "https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?format=json205361747&platform=yqq&cid=205361747&songmid=003lghpv0jfFXG&filename=" +
//                filename + "&guid=" + GUID;
//        Request.Builder requestBuilder = new Request.Builder();
//        requestBuilder.url(tokenUrl);
//        requestBuilder.addHeader("User-Agent", QQMusicApi.USER_AGENT);
//        requestBuilder.addHeader(Constants.REFERER, "http://y.qq.com");
//        requestBuilder.get();
//        try {
//            Response response = HttpEngine.requestSync(requestBuilder.build(), useProxy());
//            String data = responseBodyToString(response);
//            JSONObject json = JSONObject.parseObject(data);
//            JSONArray sip = json.getJSONArray("sip");
//            String key = json.getString("key");
//            System.out.println(key);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * 获取专辑封面
     * @param albumid
     * @return
     */
    private String getImgUrl(String albumid) {
        return "http://imgcache.qq.com/music/photo/album_300/" +
                Long.parseLong(albumid) % 100 +
                "/300_albumpic_" + albumid + "_0.jpg";
    }
}
